package com.tonglukuaijian.survey.jsonrpc.common;

import java.io.IOException;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.googlecode.jsonrpc4j.JsonRpcHttpClient;

public class CommonJsonRpcHttpClient extends JsonRpcHttpClient {
	
	public CommonJsonRpcHttpClient(URL serviceUrl, Map<String, String> headers) {
		super(serviceUrl, headers);
	}

	public CommonJsonRpcHttpClient(URL serviceUrl) {
		super(serviceUrl);
	}

	public CommonJsonRpcHttpClient(ObjectMapper mapper, URL serviceUrl, Map<String, String> headers) {
		super(mapper, serviceUrl, headers);
	}
	
	@Override
	protected HttpURLConnection prepareConnection(Map<String, String> extraHeaders) throws IOException {
		HttpURLConnection connection = super.prepareConnection(extraHeaders);
		connection.setRequestProperty("Content-type", "application/json");
		return connection;
	}

	@Override
	public void invoke(String methodName, Object argument) throws Throwable {
		beforeInvoke(methodName, argument);
		super.invoke(methodName, argument);
		afterInvoke(methodName, argument);
		
	}

	private void afterInvoke(String methodName, Object argument) {
//		log.info(String.format("10s%:s%20s%\n20s%", "methodName", methodName, argument));
	}

	private void beforeInvoke(String methodName, Object argument) {
//		log.info(String.format("10s%:s%20s%\n20s%", "methodName", methodName, argument));
	}

	@Override
	public Object invoke(String methodName, Object argument, Type returnType) throws Throwable {
		beforeInvoke(methodName, argument);
		Object obj = super.invoke(methodName, argument, returnType);
		afterInvoke(methodName, argument);
		return obj;
	}

	@Override
	public <T> T invoke(String methodName, Object argument, Class<T> clazz) throws Throwable {
		beforeInvoke(methodName, argument);
		T obj = super.invoke(methodName, argument, clazz);
		afterInvoke(methodName, argument);
		return obj;
	}

	@Override
	public Object invoke(String methodName, Object argument, Type returnType, Map<String, String> extraHeaders) throws Throwable {
		beforeInvoke(methodName, argument);
		Object obj = super.invoke(methodName, argument, returnType, extraHeaders);
		afterInvoke(methodName, argument);
		return obj;
	}

	@Override
	public <T> T invoke(String methodName, Object argument, Class<T> clazz, Map<String, String> extraHeaders) throws Throwable {
		beforeInvoke(methodName, argument);
		T obj = super.invoke(methodName, argument, clazz, extraHeaders);
		afterInvoke(methodName, argument);
		return obj;
	}
	
	

}
